package de.uni_saarland.coli.doclists.document;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.uni_saarland.coli.doclists.index.filesystem.DiscList;
import de.uni_saarland.coli.doclists.index.filesystem.FilesystemHelper;
import de.uni_saarland.coli.doclists.index.filesystem.IToBytes;
import de.uni_saarland.coli.doclists.texttools.ITextTokenizer;

/**
 * 
 * @author stefan
 * 
 *         Index representation of the document
 */
public class IndexDocument implements IDocument, Serializable, IToBytes {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6927184112826739324L;

	private int docID;
	private List<Integer> terms;
	protected DiscList parentList;

	/**
	 * Constructor.
	 * 
	 * @param tDoc
	 *            the document
	 * @param tokenizer
	 *            a tokenizer
	 */
	public IndexDocument(ITextDocument tDoc, ITextTokenizer tokenizer) {
		this.terms = new ArrayList<Integer>();
		this.docID = tDoc.getDocID();

		tokenizer.startDocument(tDoc);
		while (tokenizer.hasNext()) {
			terms.add(tokenizer.next());
		}
		
		this.parentList = null;
	}

	/**
	 * Constructor.
	 * 
	 * @param bytes
	 *            object as byte array
	 */
	public IndexDocument(byte[] bytes) {
		this.terms = new ArrayList<Integer>();
		this.docID = FilesystemHelper.getIntFromByteArray(bytes, 0);

		for (int i = 1; i < bytes.length / 4; i++) {
			this.terms.add(FilesystemHelper.getIntFromByteArray(bytes, i));
		}
	}

	@Override
	public int getDocID() {
		return this.docID;
	}

	@Override
	public void setDocID(int id) {
		this.docID = id;
	}

	public int getTermAt(int idx) {
		if (idx < this.terms.size())
			return this.terms.get(idx);
		else
			return 0;
	}

	/**
	 * Length of document
	 * 
	 * @return document size
	 */
	public int size() {
		return this.terms.size();
	}

	@Override
	public byte[] toBytes() {
		byte[] bytes = new byte[this.terms.size() * 4 + 4];

		FilesystemHelper.addIntToByteArray(bytes, this.docID, 0);

		for (int i = 0; i < this.terms.size(); i++) {
			FilesystemHelper.addIntToByteArray(bytes, this.terms.get(i), i + 4);
		}

		return bytes;
	}

	@Override
	public String toString() {

		return "" + this.getDocID() + "(" + this.terms.size() + ")";
	}

	@Override
	/**
	 * Sets the document id to the index
	 * 
	 * @param idx the index
	 */
	public void setListIDX(int idx) {
		this.docID = idx;
	}
	
	@Override
	/**
	 * Gets the document id to the index
	 * 
	 * return the index
	 */
	public int getListIDX() {
		return this.docID;
	}
	
	@Override
	public void setDistList(DiscList list) {
		this.parentList = list;
	}

}
